package com.hmdp.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author 张一恒
 * @version 1.0
 * @description: redis全局唯一id生成工具类
 * @date 2022/11/22 10:46
 */
@Slf4j
@Component
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    //开始时间戳
    private static final long BEGIN_TIMESTAMP = 1640995200L;

    //序列号的移动位数
    private static final int COUNT_BITS = 32;

    /**
     * @description 生成方法
     * @param keyPrefix
     * @return long
     * @author 31115
     * @date 2022/11/22 10:48
     */
    public long nexId(String keyPrefix){
        //生成时间戳
        LocalDateTime nowTime = LocalDateTime.now();
        long nowSecond = nowTime.toEpochSecond(ZoneOffset.UTC);
        long second = nowSecond - BEGIN_TIMESTAMP;
        //生成序列号
        //获取当前时间 精确到天
        String date = nowTime.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        //拼接返回
        return second << COUNT_BITS | count;
    }


    //获取开始时间戳
    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2022, 1, 1, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second = " + second);
    }
}
